import axios from 'axios'
import TokenGoThrough from "./releaseRouter";// 不需要验证token的路由

// 导入baseURL
import { baseURL } from './config.js'
const axiosServer = axios.create({
	baseURL,
	timeout: 30000,
})

//请求拦截器
axiosServer.interceptors.request.use(
	config => {
		if (TokenGoThrough.indexOf(config.url) !== -1) {
			// 放行
			return config;
		}
		// 设置token到authorization头部
		let token = localStorage.getItem('TOKEN')
			if (token) {
				// console.log('config.headers ',config.headers);
				config.headers['Authorization'] = token
			}

			return config
		},
		error => {
			// 对请求错误做些什么
			return Promise.reject(error)
	}
)

//响应拦截器
axiosServer.interceptors.response.use(
	function (response) {
        const token = response.headers.get('Authorization');
		// 单token可视情况替换
        if (token) {
            localStorage.setItem("TOKEN", token);
        }
        if (response.data.code === -99 || response.data.code === -98) {
			// 操作失败的情况
            localStorage.clear();
            return;
        }
        return response.data;
    },
	function (error) {
		// 对响应错误做点什么
		return Promise.reject(error)
	}
)
export default axiosServer
